<template>
    <!-- <div class="list">
        <button @click="submit">发送</button>
        <div class="item" v-for="item in chatlist">{{ item }}</div>
    </div> -->
    <Bubble.List :roles="roles" :style="{ maxHeight: 300 }" :items="chatlist" />
    <Sender v-model:value="currQuestion" @submit="submit" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
// 图标
import { UserOutlined } from '@ant-design/icons-vue';
import { Bubble, Sender, useXAgent, useXChat } from 'ant-design-x-vue';
type chatMsg = {
    key: string,
    role: string,
    content: string,
    loading: boolean
}
let chatlist: chatMsg[] = ref([]);
// 会话角色
const roles: (typeof Bubble.List)['roles'] = {
    ai: {
        placement: 'start',
        avatar: { icon: UserOutlined, style: { background: '#fde3cf' } },
    },
    local: {
        placement: 'end',
        avatar: { icon: UserOutlined, style: { background: '#87d068' } },
    },
};
// 发送消息
const currQuestion = ref('')
// 创建客户端
const [agent] = useXAgent({
    baseURL: "http://134.84.205.17:10081/v1/chat-messages", // 模型服务地址
    // model: "gpt-4", // 指定模型类型
    dangerouslyApiKey: "Bearer app-6gKPSIz3vBUMADs6UzLeO8lI", // 密钥（需注意安全风险）
    // headers: {
    //     'Authorization': `Bearer app-6gKPSIz3vBUMADs6UzLeO8lI`
    // },
});
//当前是否正在回答问题中....
const isFirstMsg = ref(true)
const submit = () => {
    // 插入问题
    chatlist.value.push({
        key: 'id',
        role: 'local',
        content: currQuestion.value,
        loading: false
    })
    // 插入loading
    chatlist.value.push({
        key: 'id',
        role: 'ai',
        content: '',
        loading: true
    })
    // 清空文本框
    // currQuestion.value = ''
    // 发送用户输入
    agent.value.request(
        {
            user: 'test',
            query: "人社局电话?", //用户输入/提问内容。
            inputs: { x2: '深度思考' },
            response_mode: "streaming"

        },
        {
            onUpdate: (res: any) => {
                // 流式更新：逐字显示回答
                let data = JSON.parse(res.data)
                if (data.event === 'message') {
                    let { length } = chatlist.value
                    let currAnswer = chatlist.value[length - 1];
                    currAnswer.loading = false;
                    let { content } = currAnswer
                    currAnswer.content = (content += data.answer)
                }

            },
            onSuccess: (finalResponse) => {
                // 最终完整响应
                console.log("最终结果:", finalResponse);
                isFirstMsg.value = true
            },
            onError: (error) => {
                // 错误处理
                console.error("请求失败:", error);
            },
        }
    );
}

</script>